package com.dw.love.dwade.view.adapter;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.blankj.utilcode.util.ScreenUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.gifdecoder.GifDecoder;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.load.resource.gif.GifDrawable;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.GlideDrawableImageViewTarget;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.target.Target;
import com.dw.love.dwade.R;
import com.dw.love.dwade.data.ImageWade;
import com.dw.love.dwade.view.adapter.viewholder.HomePicViewHolder;

import java.util.List;

/**
 * Created by luozizhao on 2018/6/14.
 */

public class HomePicAdapter extends RecyclerView.Adapter {

    private Context mContext;
    private List<ImageWade> mImageWadeList;
    protected boolean isScrolling = false;
    public static final int SPACE = 8;
    private OnClickImageView mOnClickImageListener;
    private Handler handler = new Handler();
    private int MESSAGE_SUCCESS = 1;


    public HomePicAdapter(List<ImageWade> imageWadeList, Context mContext) {
        this.mImageWadeList = imageWadeList;
        this.mContext = mContext;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.rv_item_home_pic, null);
        HomePicViewHolder homePicViewHolder = new HomePicViewHolder(view);
        return homePicViewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, final int position) {
        final HomePicViewHolder viewHolder = (HomePicViewHolder) holder;
 /*       ViewGroup.LayoutParams layoutParams = viewHolder.getImageView().getLayoutParams();
        int width = (ScreenUtils.getScreenWidth() - 3*SPACE) / 2;
        int height = layoutParams.height;
        layoutParams.width = width;
        viewHolder.getImageView().setLayoutParams(layoutParams);*/

        final ImageView imageView = viewHolder.getImageView();

     /*   Bitmap bitmap = LruCachePicUtils.getInstants().getBitmap(mImageWadeList.get(position).getIcon());
        if (bitmap == null) {
            Bitmap bitmap1 = BitmapUtils.decodeSampleSizeFormResoure(mContext.getResources(), mImageWadeList.get(position).getIcon(), 200, 200);
            LruCachePicUtils.getInstants().setBitmap(mImgRes[position], bitmap1);
        }
        LruCachePicUtils.getInstants().loadImageRes(imageView, mImgRes[position]);*/


        Target<Bitmap> target = new SimpleTarget<Bitmap>() {
            @Override
            public void onResourceReady(Bitmap bitmap, GlideAnimation glideAnimation) {
                //等比例缩放
                if (bitmap!=null) {
                    int height = bitmap.getHeight();
                    int width = bitmap.getWidth();
                    ViewGroup.LayoutParams layoutParams = imageView.getLayoutParams();
                    int height1 = layoutParams.height;
                    int weight1 = (ScreenUtils.getScreenWidth() - 8*4) / 2; // 减去图片间隔
                    float scaleH = ((float)height1 / (float)height);
                    float scaleW = ((float)weight1 / (float)width);
                    //等比例缩放关键代码
                    Matrix matrix = new Matrix();
                    matrix.postScale(scaleW,scaleH);
                    Bitmap bitmap1 = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
                    imageView.setImageBitmap(bitmap1);
                }else {
                    imageView.setImageResource(R.drawable.icon_placeholder);
                }

            }
        };
        String path = mImageWadeList.get(position).getIcon();
        if (path.endsWith(".jpg")) {
            Glide.with(mContext).load(path).asBitmap()/*.placeholder(R.drawable.icon_placeholder)*/.into(target);
        }/*else if (path.endsWith(".gif")){
            Glide.with(mContext).load(path).asGif().*//*.placeholder(R.drawable.icon_placeholder)*//*into(imageView);
        }*/else if (path.endsWith(".gif")) {
            Glide.with(mContext).load(path)
                    .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                    .listener(new RequestListener<String, GlideDrawable>() {
                        @Override
                        public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
                            return false;
                        }

                        @Override
                        public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                            int duration = 0;
                            // 计算动画时长
                            GifDrawable drawable = (GifDrawable) resource;
                            GifDecoder decoder = drawable.getDecoder();
                            for (int i = 0; i < drawable.getFrameCount(); i++) {
                                duration += decoder.getDelay(i);
                            }
                            //发送延时消息，通知动画结束
                            handler.sendEmptyMessageDelayed(MESSAGE_SUCCESS,
                                    duration);
                            return false;
                        }
                    }).into(new GlideDrawableImageViewTarget(imageView, 1));

        }


        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mOnClickImageListener.clickItem(mImageWadeList.get(position).getIcon(),position);
            }
        });

    }

    @Override
    public int getItemCount() {
        if (mImageWadeList != null) {
            return mImageWadeList.size();
        }
        return 0;
    }

    public void setScrolling(boolean scrolling) {
        isScrolling = scrolling;
    }



    public void setOnClickImageListener(OnClickImageView mOnClickImageListener){
        this.mOnClickImageListener = mOnClickImageListener;
    }

    public interface OnClickImageView{
        void clickItem(String path, int position);
    }
}
